package com.langyiquan.service.impl;

import com.langyiquan.config.KingttoResource;
import com.langyiquan.enums.SmsPlatform;
import com.langyiquan.enums.YesOrNo;
import com.langyiquan.mapper.SmsLogMapper;
import com.langyiquan.pojo.SmsLog;
import com.langyiquan.service.SmsService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

public class KingttoSmsServiceImpl implements SmsService {

    @Autowired
    private KingttoResource kingttoResource;

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Autowired
    private Sid sid;

    public void sendSms(String mobile) {
        System.out.println("mobile:"+mobile);
        String company = kingttoResource.getSign();
        String code = Math.random() * 9000 + 1000 + "";
        String content = company+String.format(kingttoResource.getPassportTemplate(), code);

        try {
            StringBuffer send = new StringBuffer();
            send.append("action=send");
            send.append("&userid=").append(kingttoResource.getUserid());
            send.append("&account=").append(URLEncoder.encode(kingttoResource.getAccount()));
            send.append("&password=").append(
                    URLEncoder.encode(kingttoResource.getPassword(), "UTF-8"));
            send.append("&mobile=").append(mobile);
            send.append("&content=").append(
                    URLEncoder.encode(content, "UTF-8"));

            StringBuffer receive = new StringBuffer();
            BufferedWriter wr = null;
            try {

                URL url = new URL(kingttoResource.getUrl());
                HttpURLConnection URLConn = (HttpURLConnection) url
                        .openConnection();

                URLConn.setDoOutput(true);
                URLConn.setDoInput(true);
                ((HttpURLConnection) URLConn).setRequestMethod("POST");
                URLConn.setUseCaches(false);
                URLConn.setAllowUserInteraction(true);
                HttpURLConnection.setFollowRedirects(true);
                URLConn.setInstanceFollowRedirects(true);

                URLConn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                URLConn.setRequestProperty("Content-Length", String
                        .valueOf(send.toString().getBytes().length));

                DataOutputStream dos = new DataOutputStream(URLConn
                        .getOutputStream());
                dos.writeBytes(send.toString());

                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        URLConn.getInputStream(), "UTF-8"));
                String line;
                while ((line = rd.readLine()) != null) {
                    receive.append(line).append("\r\n");
                }
                rd.close();
            } catch (IOException e) {
                _addSmsLog(mobile,content,YesOrNo.NO.type, e.getMessage());
            } finally {
                if (wr != null) {
                    try {
                        wr.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    wr = null;
                }
            }

            _addSmsLog(mobile,content,YesOrNo.YES.type,"");


        } catch (Exception e) {
            _addSmsLog(mobile,content,YesOrNo.NO.type, "编码异常");
        }
    }


    private void _addSmsLog(String mobile, String content, Integer result,String errSms){
        SmsLog smsLog = new SmsLog();
        smsLog.setId(sid.nextShort());
        smsLog.setMobile(mobile);
        smsLog.setContent(content);
        smsLog.setResult(result);
        smsLog.setErrMsg(errSms);
        smsLog.setResource(SmsPlatform.KINGTTO.type);
        smsLog.setCreatedTime(new Date());
        smsLogMapper.insert(smsLog);
    }

}

